package com.ybzl.common.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.SimpleDateFormat;

public class JSONUtil {

    private static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private static ObjectMapper objectMapper;

    public static ObjectMapper getInstance() {
        if (null == objectMapper) {
            objectMapper = new ObjectMapper();
            objectMapper.setDateFormat(new SimpleDateFormat(TIME_FORMAT));
            // 属性对不上时不报错
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }
        return objectMapper;
    }

    public static <T> T string4Object(String json, Class<T> classOfT) {
        try {
            return getInstance().readValue(json, classOfT);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String toString(Object obj) {
        try {
            return getInstance().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
